﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace ArcSWATMGT
{
    class Project : IDisposable
    {
        public Project(string projectMdb, string swatMdb)
        {
            _swatMdb = swatMdb;
            _projectMdb = projectMdb;
        }

        private string _projectMdb;
        private string _swatMdb;
        private OleDbConnection _projectCon = null;
        private OleDbConnection _swatCon = null;

        public void ExecuteNonQuery(string sql)
        {
            System.Diagnostics.Debug.WriteLine(sql);

            if (ProjectDatabaseConnection.State != ConnectionState.Open) ProjectDatabaseConnection.Open();
            using (OleDbCommand cmd = new OleDbCommand(sql, ProjectDatabaseConnection))
            {
                cmd.ExecuteNonQuery();
            }            
        }

        public DataTable  GetSWATTable(string sql)
        {
            System.Diagnostics.Debug.WriteLine(sql);
            DataTable dt = new DataTable();
            OleDbDataAdapter da = new OleDbDataAdapter(sql, SWATDatabaseConnection);
            da.Fill(dt);
            return dt;
        }

        public DataTable GetProjectTable(string sql)
        {
            System.Diagnostics.Debug.WriteLine(sql);
            DataTable dt = new DataTable();
            OleDbDataAdapter da = new OleDbDataAdapter(sql, ProjectDatabaseConnection);
            da.Fill(dt);
            return dt;
        }

        private OleDbConnection ProjectDatabaseConnection
        {
            get
            {
                if (_projectCon == null)
                    _projectCon = new OleDbConnection(ConnectionStringFromMDBFile(_projectMdb));
                return _projectCon;
            }
        }

        private OleDbConnection SWATDatabaseConnection
        {
            get
            {
                if (_swatCon == null)
                    _swatCon = new OleDbConnection(ConnectionStringFromMDBFile(_swatMdb));
                return _swatCon;
            }
        }

        private static string ConnectionStringFromMDBFile(string mdb)
        {
            if (System.IO.File.Exists(mdb))
            {
                OleDbConnectionStringBuilder b = new OleDbConnectionStringBuilder();
                b.DataSource = mdb;
                b.Provider = "Microsoft.Jet.OLEDB.4.0";
                return b.ConnectionString;
            }
            throw new Exception(mdb + " doesn't exist!");
        }

        private MGT _mgt = null;

        public MGT MGT { get { if (_mgt == null) _mgt = new MGT(this); return _mgt; } }

        public void Dispose()
        {
            if (_swatCon != null && _swatCon.State != ConnectionState.Closed) _swatCon.Close();
            if (_projectCon != null && _projectCon.State != ConnectionState.Closed) _projectCon.Close();
        }
    }
}
